//
//  WJRefreshControl.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/6.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

let kOffsetY:CGFloat = -60

class WJRefreshControl: UIRefreshControl {

       override init() {
        super.init()
        
        setUpUI()
        
     }

//    override func beginRefreshing() {
//        super.beginRefreshing()
//        refreshView.startLoading()
//    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.endLoading()
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let originY = frame.origin.y
        
        if originY > 0 {
            return
        }
        
        if refreshing {
            refreshView.startLoading()
        }
        
        if originY < kOffsetY && refreshView.rotateFlag == false {
            refreshView.rotateFlag = true
        }
        
        if originY > kOffsetY && refreshView.rotateFlag == true {
            refreshView.rotateFlag = false
        }
        
    }
    
    private func setUpUI () {
        
        tintColor = UIColor.clearColor()

        // 1.添加控件
        addSubview(refreshView)
        
        // 2.设置约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
        // 3.添加通知
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    /// 懒加载refreshView
//    private lazy var refreshView:WJRefreshView = {
//        
//        let refreshView = WJRefreshView.getRefreshView()
//       
//        return refreshView
//    }()
    private lazy var refreshView: WJRefreshView = WJRefreshView.getRefreshView()
}

// 负责视图的显示及动画
// 类方法加载xib
class WJRefreshView: UIView {
    // 转轮
    @IBOutlet weak var loadingIcon: UIImageView!
    // 加载标签
    @IBOutlet weak var loadingLabel: UILabel!
    
    // 下拉视图
    @IBOutlet weak var tipView: UIView!
    // 下拉箭头
    @IBOutlet weak var tipIcon: UIImageView!
    
    var rotateFlag:Bool = false {
        didSet {
            startAnimation()
        }
    }
    
    private class func getRefreshView () -> WJRefreshView {
       return NSBundle.mainBundle().loadNibNamed("WJRefreshView", owner: nil, options: nil).last as! WJRefreshView
    }
    
    // 要改变形变属性，不能用核心动画
    private func startAnimation() {
        
        var angle:CGFloat = CGFloat(M_PI)
        
        if rotateFlag == true {
            angle = CGFloat(M_PI) - 0.01
        } else {
            angle = -(CGFloat(M_PI) - 0.01)
        }
        
        // 块代码中的旋转是就近原则，默认是顺时针旋转
        UIView.animateWithDuration(1.0) { () -> Void in
             self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }

    }
    
/// 开始刷新
   private func startLoading() {
    
    // 如果存在刷新动画
    if loadingIcon.layer.animationForKey("loading") != nil {
        return
    }
       
        tipView.hidden = true
        loadingIcon.hidden = false
        loadingLabel.hidden = false
    
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 2
    
        loadingIcon.layer.addAnimation(anim, forKey: "loading")
    }
/// 结束刷新
   private func endLoading() {
        tipView.hidden = false
        loadingIcon.hidden = true
        loadingLabel.hidden = true
    
        loadingIcon.layer.removeAllAnimations()
    }
    
}
